import React, {Component} from 'react'
import {Block} from 'fs-flex';
import {Button, InputItem, Toast, WingBlank} from 'antd-mobile';
import {createForm} from 'rc-form';
import {connect} from 'dva'
import Header from '../../components/Header/index';
import VerificationCode from '../../components/VerificationCode/index';
// import styles from './index.less';
import PaihaoService from '../../services/paihaoService';
import ViewMyQueueService from '../../services/viewMyQueueService'
import Canstant from '../../utils/constant'
import qs from 'qs'

// 排号
class PaiHao extends Component {
  state = {
    reservation_type: null,//预约类型
    businessType: null,//业务ID
    businessTypeName: null,//业务名称
    date: null,//日期-
    timeSlotId: null,//时段ID
    startTime: null,//开始时间
    endTime: null,//结束时间

  }

  async componentDidMount() {
    const {location} = this.props
    const {businessType} = qs.parse(location.search.split('?')[1])
    const {d} = qs.parse(location.search.split('&')[1])
    const {r} = qs.parse(location.search.split('&')[2])
    const {t} = qs.parse(location.search.split('&')[3])
    const {s} = qs.parse(location.search.split('&')[4])
    const {e} = qs.parse(location.search.split('&')[5])
    this.setState({
      reservation_type: r,
      businessType: businessType,
      date: d,
      timeSlotId: t,
      startTime: s,
      endTime: e,
    })
    let business = await PaihaoService.queryBusinessTypeName(businessType)
    if (business.code === Canstant.responseOK) {
      this.setState({
        businessTypeName: business.data.busitype,
      })
    }
  }

  // 电话号码输入监听
  phoneOnChange = (rule, val, callback) => {
    if (!val) {
      callback(new Error('请输入手机号码'));
    }
    var isPhone = /^1\d{10}$/;//手机号码
    if (isPhone.test(val.replace(/\s+/g, ""))) {
      callback();
    } else {
      callback(new Error('输入手机号码格式错误'));
    }
  }

  // 验证码输入框change
  verificationCodeChange = (verificationCode, phoneNumber) => {
    this.setState({verificationCodeVal: verificationCode, phoneNumber: phoneNumber})
  }


  async appointment() {
    const {
      verificationCodeVal, phoneNumber, businessType,
      reservation_type,
      businessTypeName,
      date,
      timeSlotId,
      startTime,
      endTime,
    } = this.state
    const {name} = this.props.form.getFieldsValue()

    if (!name) {
      Toast.fail('请填写姓名', 1)
      return
    }

    if (!phoneNumber) {
      Toast.fail('请填写电话号码', 1)
      return
    } else {
      var isPhone = /^1\d{10}$/;//手机号码
      if (!isPhone.test(phoneNumber.replace(/\s+/g, ""))) {
        Toast.fail('请填写正确电话号码', 1)
        return
      }
    }
    if (!verificationCodeVal) {
      Toast.fail('请输入短信验证码', 1)
      return
    }

    const {code, msg} = await PaihaoService.createPaihao({
      mobile: phoneNumber.replace(/\s+/g, ""),
      checkCode: verificationCodeVal,//验证码
      busiType: businessType,//业务类型
      busiTypeName: businessTypeName,//业务名称
      reservationType: reservation_type,//预约类型
      name: name,
      queueDate: date,//日期-
      queueTimeSloeId: timeSlotId,//时段ID
      queueTimeSloeStart: startTime,//开始时间
      queueTimeSloeEnd: endTime,//结束时间
    });
    if (code === Canstant.responseOK) {
      Toast.success('排号成功', 1)

      let result = await ViewMyQueueService.myQueueInfo({mobile: phoneNumber.replace(/\s+/g, ""),checkCode: verificationCodeVal
      });
      console.log("push===result: " + result)
      if (result.code === Canstant.responseOK) {
        setTimeout(() => {
          this.props.history.push({pathname: '/my', state: {data: result.data}})
        }, 1000);
      }

      //TODO 路由跳转
    } else {
      Toast.fail(msg ? msg : '排号失败，请重新尝试！')
    }
  }


  render() {
    const {form: {getFieldProps, getFieldError}, history} = this.props
    return (
      <Block vf>
        <Block>
          <Header needBack='true' history={history} title='排号'/>
          <Block vf>
            <WingBlank>
              <Block vf mt={10}>
                <Block fs={14}>姓名（必填）</Block>
                <Block mt={5}>
                  <InputItem
                    {...getFieldProps('name', {
                      rules: [
                        {required: true, message: '请填写姓名'},
                      ]
                    })}
                    error={!!getFieldError('name')}
                    onErrorClick={() => {
                      Toast.fail(getFieldError('name'), 1);
                    }}
                    placeholder="姓名"
                  />
                </Block>
              </Block>

              <Block mt={10}>
                <VerificationCode
                  props={this.props}
                  verificationCodeChange={this.verificationCodeChange}
                  btnText='发送验证码'/>
              </Block>

              <Block wf mt={15} style={{paddingBottom: '15px'}}>
                <Block f='3'></Block>
                <Block f='4'><Button a='c' f='c' size='small' type="primary"
                                     onClick={this.appointment.bind(this)}>预约排号</Button></Block>
                <Block f='3'></Block>
              </Block>
            </WingBlank>
          </Block>
        </Block>
      </Block>
    )
  }
}

export default connect()(createForm()(PaiHao))
